package org.cid54.jshopper.service.impl;

import java.util.Collections;
import java.util.List;
import org.cid54.jshopper.dao.ShopItemDao;
import org.cid54.jshopper.dao.ShoppingListDao;
import org.cid54.jshopper.dao.UserDao;
import org.cid54.jshopper.dao.UserGroupDao;
import org.cid54.jshopper.model.ShopItem;
import org.cid54.jshopper.model.ShoppingList;
import org.cid54.jshopper.model.UserGroup;
import org.cid54.jshopper.service.ShoppingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author fgo
 */
@Service
@Transactional
public class ShoppingListServiceImpl implements ShoppingListService {

    @Autowired
    private ShoppingListDao shoppingListDao;
    @Autowired
    private ShopItemDao shopItemDao;
    @Autowired
    private UserGroupDao userGroupDao;
    @Autowired
    private UserDao userDao;

    @Override
    public ShoppingList getShoppingListById(long shoppingListId) {

        ShoppingList s = this.shoppingListDao.findByIdWithShopItems(shoppingListId);
        return s;
    }

    @Override
    public void create(ShoppingList list) {
        list.setUserGroup(this.userGroupDao.findByName(list.getUserGroup().getName()));
        this.shoppingListDao.create(list);
    }

    @Override
    public void update(long shoppingListId, ShoppingList list) {

        ShoppingList dbList = this.shoppingListDao.findById(shoppingListId);

        dbList.setName(list.getName());
        dbList.setUserGroup(this.userGroupDao.findByName(list.getUserGroup().getName()));

        this.shoppingListDao.update(dbList);

    }

    @Override
    public void delete(long shoppingListId) {

        ShoppingList list = this.shoppingListDao.findById(shoppingListId);

        this.shoppingListDao.delete(list);

    }

    @Override
    public void deleteShopItem(long shoppingListId, long itemId) {

        ShoppingList shoppingList = this.shoppingListDao.findById(shoppingListId);

        ShopItem shopItem = this.shopItemDao.findById(itemId);

        if (shoppingList.getShopItems().contains(shopItem)) {
            this.shopItemDao.delete(shopItem);
        }

    }

    @Override
    public List<ShoppingList> getAll(long userId) {

        List<UserGroup> userGroups = this.userGroupDao.findByUser(this.userDao.findById(userId));

        if (!userGroups.isEmpty()) {

            return this.shoppingListDao.findByUserGroups(userGroups);

        } else {

            return Collections.EMPTY_LIST;

        }
    }
}
